package com.mb.common.aspect;

import com.alibaba.fastjson.JSONObject;
import com.mb.common.config.CommonConfig;
import com.mb.common.constants.APIConstants;
import com.mb.common.utils.Base64Utils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Pub API 切面
 *
 * @author michael.li
 * @create 2018-03-24 下午3:08
 **/
@Aspect
@Component
public class PubAPIAspect {
    private static final Logger logger = LoggerFactory.getLogger(PubAPIAspect.class);

    @Pointcut("execution( * com.mb.pubapi..controller.*.*(..))"
            + "&& !execution( * com.mb.mp.controller.DemoController.*(..)) "
            //+ "&& !execution( * com.mb.pubapi.sms.controller.SmsController.*(..)) "

            )
    public void apiPointCut() {
    }

    @Autowired
    private CommonConfig commonConfig;

    /**
     * 切面处理
     * @param pjp
     * @return
     */
    @Around("apiPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String action = request.getRequestURI().replace(request.getContextPath(), "");
        logger.info("pubAPI request action :"+action);
        String resp = "";
        try {
            String reqData = request.getParameter("reqData");
            logger.info("pubAPI reqData :"+reqData);
            /*
            String sign = request.getParameter("sign");
            logger.info("pubAPI sign :"+sign);
            long timestamp = Long.parseLong(request.getParameter("ts"));
            logger.info("pubAPI timestamp :"+timestamp);
            */
            String rawdata = Base64Utils.decode(reqData);
            logger.info("pubAPI reqData rawdata :"+rawdata);

            /*
            //检查时间戳
            long currTimestamp = System.currentTimeMillis();
            //如果请求时间大于1分钟，则判定为不合法交易
            if((currTimestamp - timestamp) > 6000*1000){
                return APIConstants.legalTimeStampError;
            }

            //检查签名

            String appsec = commonConfig.getSignKey();
            String md5 = MD5UtilObject.getFileMD5String((rawdata + appsec).getBytes());
            if(!md5.equalsIgnoreCase(sign)){
                logger.info("server sign :"+md5 +", client sign :"+sign);
                return APIConstants.legalSignError;
            }
            */

            JSONObject reqDataJson = JSONObject.parseObject(rawdata);
            request.setAttribute("reqData",reqDataJson);

            String proceedRet = (String)pjp.proceed();
            logger.info("pubAPI proceedRet :"+proceedRet);

            if(StringUtils.isEmpty(proceedRet)){
                resp = APIConstants.success;
            }else {
                resp = Base64Utils.encode(proceedRet);
            }
        } catch (Throwable throwable) {
            logger.error("pubAPI APIAspect doAround Exception",throwable);
            resp = APIConstants.commError;
        }
        return resp;
    }
}
